package com.mrdeer.web.controller.app;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mrdeer.common.JSONResult;
import com.mrdeer.common.constants.MemberConstant;
import com.mrdeer.common.entity.sys.Member;
import com.mrdeer.common.exception.BusinessException;
import com.mrdeer.common.tools.RedisTemplateHelper;
import com.mrdeer.common.tools.SnowFlakeUtil;
import com.mrdeer.web.service.sys.SysMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

@Slf4j
@CacheConfig(cacheNames = "member")
@RequestMapping("/mrdeer/app/member")
@Api(tags = "会员管理接口")
@Transactional
public class AppMemberController {

    @Resource
    private SysMemberService sysMemberService;

    @Resource
    private RedisTemplateHelper redisTemplate;

    @RequestMapping(value = "/getByCondition/{page}/{pageSize}", method = RequestMethod.GET)
    @ApiOperation(value = "多条件分页获取")
    public JSONResult getByCondition(Member member, @PathVariable Integer page, @PathVariable Integer pageSize) {
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(member.getUsername())) {
            queryWrapper.eq("username", member.getUsername());
        }
        IPage<Member> memberIPage = sysMemberService.page(new Page<Member>(page, pageSize), queryWrapper);
        return JSONResult.ok(memberIPage);
    }

    @RequestMapping(value = "/admin/add", method = RequestMethod.POST)
    @ApiOperation(value = "添加用户")
    public JSONResult add(@Valid Member member) {
        if (sysMemberService.getOne(new QueryWrapper<Member>().eq("mobile", member.getMobile())) != null) {
            throw new BusinessException("该手机号已被注册");
        }
        Long uid = SnowFlakeUtil.nextId();
        //Username/uid邀请码
        member.setUsername(uid.toString()).setInviteCode(Long.toString(uid, 32).toUpperCase());
        sysMemberService.save(member);
        return JSONResult.ok("添加成功");
    }

    @RequestMapping(value = "/admin/edit", method = RequestMethod.POST)
    @ApiOperation(value = "管理员修改资料", notes = "需要通过id获取原用户信息 需要username更新缓存")
    public JSONResult edit(@Valid Member m) {
        Member old = sysMemberService.getById(m.getId());
        m.setUsername(old.getUsername()).setPassword(old.getPassword());
        //若修改了手机和邮箱判断是否唯一
        if (!old.getMobile().equals(m.getMobile()) && sysMemberService.getOne(new QueryWrapper<Member>().eq("mobile", m.getMobile())) != null) {
            return JSONResult.errorMsg("该手机号已绑定其它账户");
        }
        sysMemberService.updateById(m);
        return JSONResult.ok("修改成功");
    }

    @RequestMapping(value = "/admin/status", method = RequestMethod.POST)
    @ApiOperation(value = "后台禁用用户")
    public JSONResult disable(@RequestParam String userId, @RequestParam Boolean enable) {
        Member member = sysMemberService.getById(userId);
        if (member == null) {
            return JSONResult.errorMsg("会员不存在");
        }
        if (enable) {
            member.setStatus(MemberConstant.MEMBER_STATUS_NORMAL);
        } else {
            member.setStatus(MemberConstant.MEMBER_STATUS_LOCK);
        }
        sysMemberService.updateById(member);
        //手动更新缓存
        redisTemplate.delete("member::" + member.getUsername());
        return JSONResult.ok("操作成功");
    }

    @RequestMapping(value = "/delByIds", method = RequestMethod.POST)
    @ApiOperation(value = "批量通过ids删除")
    public JSONResult delAllByIds(@RequestParam List<String> ids) {
        sysMemberService.removeByIds(ids);
        redisTemplate.delete("member::*");
        return JSONResult.ok("批量通过id删除数据成功");
    }
}
